package com.zf.yichat.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

 import com.zf.yichat.dto.FanliGiveAndGoodsDetailDto;
import com.zf.yichat.dto.FanliGoodsReceiveDto;
import com.zf.yichat.dto.FanliListResp;
import com.zf.yichat.dto.VideoDto;
import com.zf.yichat.mapper.FanliDailyMapper;
import com.zf.yichat.mapper.FanliGoodsGiveMapper;
import com.zf.yichat.mapper.FanliGoodsReceiveMapper;
import com.zf.yichat.mapper.UserInviteMapper;
import com.zf.yichat.model.FanliDaily;
import com.zf.yichat.model.FanliGoodsGive;
import com.zf.yichat.model.FanliGoodsReceive;
import com.zf.yichat.model.User;
import com.zf.yichat.service.BalanceService;
import com.zf.yichat.service.FanliService;
import com.zf.yichat.service.UserService;
import com.zf.yichat.service.config.ConfigSet;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.NumberUtils;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.utils.yunshangshuju.DoItemCpsUrlReq;
import com.zf.yichat.utils.yunshangshuju.GetJdUnionItemsReq;
import com.zf.yichat.utils.yunshangshuju.GetJfItemsReq;
import com.zf.yichat.utils.yunshangshuju.GetTbkQdBeiAnResp;
import com.zf.yichat.utils.yunshangshuju.GetTrillItemListReq;
import com.zf.yichat.utils.yunshangshuju.GetTrillItemListResp;
import com.zf.yichat.utils.yunshangshuju.ItemHighCommissionPromotionLinkByTpwdReq;
import com.zf.yichat.utils.yunshangshuju.ItemHighCommissionPromotionLinkReq;
import com.zf.yichat.utils.yunshangshuju.ItemHighCommissionPromotionLinkResp;
import com.zf.yichat.utils.yunshangshuju.TbkOrderDetailsGetReq;
import com.zf.yichat.utils.yunshangshuju.TbkrelationbeianReq;
import com.zf.yichat.utils.yunshangshuju.TbkrelationbeianResp;
import com.zf.yichat.utils.yunshangshuju.YsClient;
import com.zf.yichat.vo.BalanceType;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.util.Contracts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Resource;


import tk.mybatis.mapper.entity.Example;

/**
 * @date Created in 2020/11/9 14:10
 * @description
 */
@Service
public class FanliServiceImpl implements FanliService {
    private static Logger logger = LoggerFactory.getLogger(FanliServiceImpl.class);

    @Autowired
    ConfigSet configSet;
    @Autowired
    BalanceService balanceService;
    @Autowired
    UserService userService;
    @Resource
    UserInviteMapper userInviteMapper;
    @Resource
    FanliGoodsReceiveMapper fanliGoodsReceiveMapper;
    @Resource
    FanliGoodsGiveMapper fanliGoodsGiveMapper;
    @Resource
    FanliDailyMapper fanliDailyMapper;

    /**
     * taobao.tbk.dg.material.optional( 淘宝客-推广者-物料搜索 )
     *
     * @return
     */
    @Override
    public FsResponse dgMaterialOptional(FsPage page, String query) {
        return null;
    }

    /**
     * taobao.tbk.dg.optimus.material( 淘宝客-推广者-物料精选 )
     *
     * @param page
     * @return
     */
    @Override
    public FsResponse dgOptimusMaterial(FsPage page) {
//        TaobaoClient client = new DefaultTaobaoClient(configSet.getTbk().getUrl(), configSet.getTbk().getAppKey(), configSet.getTbk().getAppSecret());
//        TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
//        if (Objects.nonNull(page)) {
//            req.setPageSize(page.getPageSize().longValue());
//            req.setPageNo(page.getPageNo().longValue());
//        }
//        req.setMaterialId(27446L);
//        req.setAdzoneId(110863550207L);
//        TbkDgOptimusMaterialResponse rsp;
//        try {
//            rsp = client.execute(req);
//        } catch (ApiException e) {
//            e.printStackTrace();
//            throw new RuntimeException("物料精选异常：" + e.getMessage());
//        }
//        if (rsp.isSuccess()) {
//            return FsResponseGen.successData(transFanliListResp(rsp.getResultList()));
//        } else {
//            return FsResponseGen.failMsg(rsp.getSubMsg());
//        }
        return null;
    }

    /**
     * taobao.tbk.item.info.get( 淘宝客-公用-淘宝客商品详情查询(简版) )
     *
     * @return
     */
    private FsResponse itemInfoGet(ItemHighCommissionPromotionLinkResp resp) {
//        TaobaoClient client = new DefaultTaobaoClient(configSet.getTbk().getUrl(), configSet.getTbk().getAppKey(), configSet.getTbk().getAppSecret());
////        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
////        req.setNumIids(String.valueOf(resp.getItem_id()));
////        TbkItemInfoGetResponse rsp;
////        try {
////            rsp = client.execute(req);
////        } catch (ApiException e) {
////            e.printStackTrace();
////            throw new RuntimeException("商品查询异常：" + e.getMessage());
////        }
////        if (rsp.isSuccess()) {
////            return FsResponseGen.successData(transFanliListResp(rsp.getResults().get(0), resp));
////        } else {
////            return FsResponseGen.failMsg(rsp.getSubMsg());
////        }
        return null;
    }
//
//    private List<FanliListResp> transFanliListResp(TbkItemInfoGetResponse.NTbkItem v, ItemHighCommissionPromotionLinkResp v2) {
////        List<FanliListResp> respList = new ArrayList<>();
////        FanliListResp resp = new FanliListResp();
////        resp.setItemId(String.valueOf(v2.getItem_id()));
////        if (StringUtils.isNotEmpty(v.getPictUrl()) && !v.getPictUrl().contains("http")) {
////            v.setPictUrl("http:" + v.getPictUrl());
////        }
////        List<String> images = v.getSmallImages();
////
////        if (Objects.nonNull(images)) {
////            List<String> imgs = images.stream().map(v3 -> {
////                if (!v3.contains("http")) {
////                    v3 = "http:" + v3;
////                }
////                return v3;
////            }).collect(Collectors.toList());
////            v.setSmallImages(imgs);
////        }
////        BigDecimal rate = new BigDecimal(Optional.ofNullable(v2.getMax_commission_rate()).orElse("0"));
////        Integer r = rate.multiply(new BigDecimal("100")).intValue();
////        resp.setCommissionRate(String.valueOf(r));
////        resp.setZkFinalPrice(v.getZkFinalPrice());
////        resp.setReservePrice(v.getReservePrice());
////        resp.setPictUrl(v.getPictUrl());
////        resp.setTitle(v.getTitle());
////        resp.setUserType(v.getUserType().intValue());
////        resp.setSmallImages(v.getSmallImages());
////
////        resp.setCouponAmount(v2.getYouhuiquan());
////        resp.setCouponShareUrl(v2.getCoupon_click_url());
////        resp.setUrl(v2.getItem_url());
////        respList.add(resp);
////        return respList;
//        return null;
//    }

    private List<VideoDto> transVideo(List<GetTrillItemListResp> list) {
        List<VideoDto> respList = new ArrayList<>();
        list.forEach(v -> {
            VideoDto dto = new VideoDto();
            //            dto.setAvatar(v.getShop_name());
            dto.setNick(v.getShop_name());
            dto.setShopId(v.getShop_id());
            dto.setCommentCount(v.getDy_video_share_count());
            dto.setContent(v.getDy_video_title());
            dto.setPath(v.getDy_video_url());
            dto.setThumbnail(v.getDynamic_image());
            dto.setPraseCount(v.getDy_video_like_count());
            //            dto.setSeconds(v.getSeconds());
            //            dto.setVideoId(v.getId());
            //            dto.setRate(video.getRate());
            //            dto.setTag(v.getTag());
            dto.setTitle(v.getShort_title());
            dto.setLinkUrl(v.getCoupon_url());
            dto.setGoodsImg("http://img.haodanku.com/" + v.getItempic_copy());
            dto.setDiscountInfo(v.getDiscount());
            dto.setGoodsPrice(v.getQuanhoujia());
            //            dto.setPacketId(v.getQuanhoujia());

            //            dto.setPraiseStatus(Objects.nonNull(selectPraiseByUserId(v.getId(), userId)) ? 1 : 0);


            FanliListResp goodsInfo = new FanliListResp();
            goodsInfo.setItemId(v.getNum_iid());
            //图片信息
            List<String> images = new ArrayList<>();
            //            images.add("http://img.haodanku.com/" + v.getItempic_copy());
            goodsInfo.setSmallImages(images);
            //佣金
            Double rateD = Optional.ofNullable(Double.valueOf(v.getTk_rates())).orElse(0d);
            BigDecimal rate = new BigDecimal(String.valueOf(rateD));
            Integer r = rate.multiply(new BigDecimal("100")).intValue();
            goodsInfo.setCommissionRate(String.valueOf(r));
            BigDecimal price = v.getPrice() == null ? BigDecimal.ZERO : v.getPrice();
            goodsInfo.setZkFinalPrice(String.valueOf(price));
            goodsInfo.setReservePrice(String.valueOf(price));
            goodsInfo.setCouponAmount(v.getCoupon_money());
            goodsInfo.setCouponShareUrl(v.getCoupon_url());
            goodsInfo.setTitle(v.getTitle());
            goodsInfo.setUrl(v.getCoupon_url());
            goodsInfo.setUserType("B".equals(v.getShop_type()) ? 1 : 0);
            if (StringUtils.isNotEmpty(v.getPic())) {
                String pic = "http://img.haodanku.com/" + v.getItempic_copy();
                goodsInfo.setPictUrl(pic);
            }
            dto.setGoodsInfo(goodsInfo);
            respList.add(dto);
        });
        return respList;
    }

    //    private static String replaceDomainAndPort(String domain, String port, String url) {
    //        String url_bak = "";
    //        if (url.indexOf("//") != -1) {
    //            String[] splitTemp = url.split("//");
    ////            url_bak = splitTemp[0] + "//";
    //            if (port != null) {
    //                url_bak = url_bak + domain + ":" + port;
    //            } else {
    //                url_bak = url_bak + domain;
    //            }
    //
    //            if (splitTemp.length >= 1 && splitTemp[1].indexOf("/") != -1) {
    //                String[] urlTemp2 = splitTemp[1].split("/");
    //                if (urlTemp2.length > 1) {
    //                    for (int i = 1; i < urlTemp2.length; i++) {
    //                        url_bak = url_bak + "/" + urlTemp2[i];
    //                    }
    //                }
    //            }
    //        }
    //        return url_bak;
    //    }

//    private List<FanliListResp> transFanliListResp(List<TbkDgOptimusMaterialResponse.MapData> list) {
//        List<FanliListResp> respList = new ArrayList<>();
//        list.forEach(v -> {
//            FanliListResp resp = new FanliListResp();
//            resp.setItemId(String.valueOf(v.getItemId()));
//            if (StringUtils.isNotEmpty(v.getPictUrl()) && !v.getPictUrl().contains("http")) {
//                v.setPictUrl("http:" + v.getPictUrl());
//            }
//            List<String> images = v.getSmallImages();
//
//            if (Objects.nonNull(images)) {
//                List<String> imgs = images.stream().map(v2 -> {
//                    if (!v2.contains("http")) {
//                        v2 = "http:" + v2;
//                    }
//                    return v2;
//                }).collect(Collectors.toList());
//                v.setSmallImages(imgs);
//            }
//            BigDecimal rate = new BigDecimal(Optional.ofNullable(v.getCommissionRate()).orElse("0"));
//            Integer r = rate.multiply(new BigDecimal("100")).intValue();
//            resp.setCommissionRate(String.valueOf(r));
//            resp.setZkFinalPrice(v.getZkFinalPrice());
//            resp.setReservePrice(v.getReservePrice());
//            resp.setCouponAmount(String.valueOf(v.getCouponAmount()));
//            resp.setCouponShareUrl(v.getCouponShareUrl());
//            resp.setPictUrl(v.getPictUrl());
//            resp.setTitle(v.getTitle());
//            resp.setUrl(v.getClickUrl());
//            resp.setUserType(v.getUserType().intValue());
//            resp.setSmallImages(v.getSmallImages());
//
//            respList.add(resp);
//        });
//        return respList;
//    }
//

    /**
     * jd.union.open.goods.jingfen.query 京粉精选商品查询接口
     *
     * @param page
     * @param query
     * @return
     */
    @Override
    public FsResponse goodsQeury(FsPage page, String query) {
          return null;
    }

    /**
     * 云商数据，京东商品转链
     *
     * @param materialId
     * @return
     */
    @Override
    public FsResponse doItemCpsUrl(String materialId) {
        DoItemCpsUrlReq req = new DoItemCpsUrlReq();
        req.setMaterialId(materialId);
        req.setPositionId(3002840551L);
        req.setKey_id("J4748733380645247");

        YsClient client = new YsClient("http://api.web.ecapi.cn/jingdong/doItemCpsUrl", configSet.getYunShang().getAppKey());
        FsResponse response;
        try {
            response = client.execute(req, Object.class);
        } catch (Exception e) {
            e.printStackTrace();
            return FsResponseGen.fail();
        }
        return response;
    }

    /**
     * 云商数据，京东商品查询
     *
     * @param page
     * @param query
     * @return
     */
    @Override
    public FsResponse getJdUnionItems(FsPage page, String query, boolean isSkuId) {
//        GetJdUnionItemsReq req = new GetJdUnionItemsReq();
//        if (isSkuId) {
//            req.setSkuIds(query);
//        } else {
//            req.setKeyword(query);
//        }
//        req.setSortName("commissionShare");
//        req.setPid("1003355351_4000372243_3002840551");
//        req.setPageIndex(page.getPageNo());
//        req.setPageSize(page.getPageSize());
//
//        YsClient client = new YsClient("http://api.web.ecapi.cn/jingdong/getJdUnionItems", configSet.getYunShang().getAppKey());
//        FsResponse response;
//        try {
//            response = client.execute(req, Object.class);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return FsResponseGen.fail();
//        }
//        if (response.isSuccess()) {
//            String jsonArray = JSONObject.parseObject(response.getData().toString()).getString("list");
//            response.setData(transFanliListRespJd(JSONArray.parseArray(jsonArray, GoodsResp.class)));
//        }
//        return response;
        return null;
    }

    /**
     * 云商数据，获取京粉精选
     *
     * @param page
     * @return
     */
    @Override
    public FsResponse getJfItems(FsPage page) {
//        GetJfItemsReq req = new GetJfItemsReq();
//        req.setEliteId(22);
//        req.setPageIndex(page.getPageNo());
//        req.setPageSize(page.getPageSize());
//
//        YsClient client = new YsClient("http://api.web.ecapi.cn/jingdong/getJfItems", configSet.getYunShang().getAppKey());
//        FsResponse response;
//        try {
//            response = client.execute(req, Object.class);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return FsResponseGen.fail();
//        }
//        if (response.isSuccess()) {
//            String jsonArray = JSONObject.parseObject(response.getData().toString()).getString("list");
//            response.setData(transFanliListRespJdJf(JSONArray.parseArray(jsonArray, JFGoodsResp.class)));
//        }
//        return response;
        return null;
    }
//
//    private List<FanliListResp> transFanliListRespJdJf(List<JFGoodsResp> list) {
////        List<FanliListResp> respList = new ArrayList<>();
////        list.forEach(v -> {
////            FanliListResp resp = new FanliListResp();
////            resp.setItemId(String.valueOf(v.getSkuId()));
////            //图片信息
////            UrlInfo[] urlInfos = v.getImageInfo().getImageList();
////            List<String> images = new ArrayList<>();
////            if (Objects.nonNull(urlInfos) && urlInfos.length > 0) {
////                //第一张为主图
////                resp.setPictUrl(urlInfos[0].getUrl());
////                //其余的为小图片
////                for (int i = 1; i < urlInfos.length; i++) {
////                    images.add(urlInfos[i].getUrl());
////                }
////            }
////            resp.setSmallImages(images);
////            //佣金
////            Double rateD = Optional.ofNullable(v.getCommissionInfo().getCommissionShare()).orElse(0d);
////            BigDecimal rate = new BigDecimal(String.valueOf(rateD));
////            Integer r = rate.multiply(new BigDecimal("100")).intValue();
////            resp.setCommissionRate(String.valueOf(r));
////            Double price = v.getPriceInfo().getPrice() == null ? 0 : v.getPriceInfo().getPrice();
////            resp.setZkFinalPrice(String.valueOf(price));
////            resp.setReservePrice(String.valueOf(price));
////            Coupon[] coupons = v.getCouponInfo().getCouponList();
////            double couponAmount = 0;
////            String couponLink = "";
////            if (Objects.nonNull(coupons) && coupons.length > 0) {
////                couponAmount = coupons[0].getDiscount();
////                couponLink = coupons[0].getLink();
////            }
////            resp.setCouponAmount(String.valueOf(couponAmount));
////            resp.setCouponShareUrl(couponLink);
////            resp.setTitle(v.getSkuName());
////            resp.setUrl(v.getMaterialUrl());
////            resp.setUserType(2);
////
////            respList.add(resp);
////        });
////        return respList;
//        return null;
//    }
//
//    private List<FanliListResp> transFanliListRespJd(List<GoodsResp> list) {
//        List<FanliListResp> respList = new ArrayList<>();
//        list.forEach(v -> {
//            FanliListResp resp = new FanliListResp();
//            resp.setItemId(String.valueOf(v.getSkuId()));
//            //图片信息
//            jd.union.open.goods.query.response.UrlInfo[] urlInfos = v.getImageInfo().getImageList();
//            List<String> images = new ArrayList<>();
//            if (Objects.nonNull(urlInfos) && urlInfos.length > 0) {
//                //第一张为主图
//                resp.setPictUrl(urlInfos[0].getUrl());
//                //其余的为小图片
//                for (int i = 1; i < urlInfos.length; i++) {
//                    images.add(urlInfos[i].getUrl());
//                }
//            }
//            resp.setSmallImages(images);
//            //佣金
//            Double rateD = Optional.ofNullable(v.getCommissionInfo().getCommissionShare()).orElse(0d);
//            BigDecimal rate = new BigDecimal(String.valueOf(rateD));
//            Integer r = rate.multiply(new BigDecimal("100")).intValue();
//            resp.setCommissionRate(String.valueOf(r));
//            Double price = v.getPriceInfo().getPrice() == null ? 0 : v.getPriceInfo().getPrice();
//            resp.setZkFinalPrice(String.valueOf(price));
//            resp.setReservePrice(String.valueOf(price));
//            jd.union.open.goods.query.response.Coupon[] coupons = v.getCouponInfo().getCouponList();
//            double couponAmount = 0;
//            String couponLink = "";
//            if (Objects.nonNull(coupons) && coupons.length > 0) {
//                couponAmount = coupons[0].getDiscount();
//                couponLink = coupons[0].getLink();
//            }
//            resp.setCouponAmount(String.valueOf(couponAmount));
//            resp.setCouponShareUrl(couponLink);
//            resp.setTitle(v.getSkuName());
//            resp.setUrl(v.getMaterialUrl());
//            resp.setUserType(2);
//
//            respList.add(resp);
//        });
//        return respList;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FsResponse checkSusccess(Long id) {
        FanliGoodsGive give = fanliGoodsGiveMapper.selectByPrimaryKey(id);
        Contracts.assertNotNull(give, "值不存在");

        if (give.getStatus() != 0 && give.getStatus() != 2) {
            return FsResponseGen.failMsg("状态错误");
        }

        give.setCheckTime(new Date());
        give.setStatus(1);
        fanliGoodsGiveMapper.updateByPrimaryKeySelective(give);

        //更新领取表
        FanliGoodsReceive receive = fanliGoodsReceiveMapper.selectByPrimaryKey(give.getGoodsId());
        receive.setUtime(new Date());
        receive.setId(give.getGoodsId());
        receive.setStatus(2);
        fanliGoodsReceiveMapper.updateByPrimaryKeySelective(receive);

        logger.debug("-------用户{}返利开始,需返利{}-----", give.getUserId(), receive.getRealMoney());
        //更新用户及其上级余额
        //首先我们抽取10%
        BigDecimal commisstion = NumberUtils.scale2HalfUp(receive.getRealMoney().multiply(new BigDecimal("0.1")));
        logger.debug("系统抽取{}", commisstion);
        BigDecimal totalCommisstion = commisstion;
        //查找其上级
        String ids = userInviteMapper.selectAncestorIds(give.getUserId());
        if (StringUtils.isNotEmpty(ids)) {
            String[] arr = ids.split(",");
            //第一个抽5%；
            BigDecimal rate = new BigDecimal("0.05");
            //第一个“,”前是空字符串
            for (int i = 1; i < arr.length; i++) {
                BigDecimal money = NumberUtils.scale2Down(receive.getRealMoney().multiply(rate).multiply(new BigDecimal(String.valueOf(Math.pow(0.5, i - 1)))));
                logger.debug("第{}级用户{}需要返利{}", i, arr[i], money);
                if (money.compareTo(new BigDecimal("0.01")) < 0) {
                    break;
                } else {
                    totalCommisstion = totalCommisstion.add(money);
                    if (totalCommisstion.compareTo(receive.getRealMoney()) > 0) {
                        totalCommisstion = totalCommisstion.subtract(money);
                        logger.error("返利金超过总额");
                        break;
                    } else {
                        balanceService.update(Long.parseLong(arr[i]), BalanceType.PACKET_FANLI_INVITE_GET, money, give.getUserId(), "下级用户返利分成");
                        logger.debug("已返利");
                    }
                }

            }
        }

        balanceService.update(give.getUserId(), BalanceType.PACKET_FANLI_GET, receive.getRealMoney().subtract(totalCommisstion), give.getId(), "返利");
        logger.debug("------返利结束，用户最终得{}------", receive.getRealMoney().subtract(totalCommisstion));

        return FsResponseGen.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FsResponse checkFail(Long id, String reason) {
        FanliGoodsGive give = fanliGoodsGiveMapper.selectByPrimaryKey(id);
        Contracts.assertNotNull(give, "值不存在");
        if (give.getStatus() != 0 && give.getStatus() != 2) {
            return FsResponseGen.failMsg("状态错误");
        }

        give.setCheckTime(new Date());
        give.setStatus(2);
        give.setRefuseReason(reason);
        fanliGoodsGiveMapper.updateByPrimaryKeySelective(give);

        //更新领取表
        FanliGoodsReceive receive = new FanliGoodsReceive();
        receive.setUtime(new Date());
        receive.setId(give.getGoodsId());
        receive.setStatus(3);
        receive.setRefuseReason(reason);
        fanliGoodsReceiveMapper.updateByPrimaryKeySelective(receive);

        return FsResponseGen.success();
    }

    @Override
    public BigDecimal countFanliMoney(BigDecimal zkFinalPrice, BigDecimal couponAmount, Integer commissionRate) {
        commissionRate = Optional.ofNullable(commissionRate).orElse(0);
        zkFinalPrice = Optional.ofNullable(zkFinalPrice).orElse(BigDecimal.ZERO);
        couponAmount = Optional.ofNullable(couponAmount).orElse(BigDecimal.ZERO);
        return NumberUtils.halfTwo(zkFinalPrice.subtract(couponAmount).multiply(new BigDecimal(commissionRate).divide(new BigDecimal("10000"))));
    }

    @Override
    public FsResponse setTbkQdBeiAn(Long userId) {
        TbkrelationbeianReq req = new TbkrelationbeianReq();
        req.setInvitercode("FZK2RU");
        req.setInfotype(1);

        YsClient client = new YsClient("https://www.ecapi.cn/index/extapi/tbkrelationbeian", configSet.getYunShang().getAppKey());
        FsResponse response;
        try {
            response = client.execute(req, GetTbkQdBeiAnResp.class);
            if (response.isSuccess()) {
                TbkrelationbeianResp getTbkQdBeiAnResp = (TbkrelationbeianResp) response.getData();
                //更新用户表
                User user = new User();
                user.setId(userId);
                user.setRelationId(getTbkQdBeiAnResp.getRelation_id());
                //                user.setSpecialId(getTbkQdBeiAnResp.getSpecial_id());
                userService.update(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return FsResponseGen.fail();
        }
        return response;
    }
    //    @Override
    //    public FsResponse setTbkQdBeiAn(Long userId) {
    //        GetTbkQdBeiAnReq req = new GetTbkQdBeiAnReq();
    //        req.setInvitercode("FZK2RU");
    //        req.setInfotype("1");
    //        req.setTbname("zhangfeng_tech");
    //
    //        YsClient client = new YsClient("http://api.web.ecapi.cn/taoke/getTbkQdBeiAn", configSet.getYunShang().getAppKey());
    //        FsResponse response;
    //        try {
    //            response = client.execute(req, GetTbkQdBeiAnResp.class);
    //            if (response.isSuccess()) {
    //                GetTbkQdBeiAnResp getTbkQdBeiAnResp = (GetTbkQdBeiAnResp) response.getData();
    //                //更新用户表
    //                User user = new User();
    //                user.setId(userId);
    //                user.setRelationId(getTbkQdBeiAnResp.getRelation_id());
    //                user.setSpecialId(getTbkQdBeiAnResp.getSpecial_id());
    //                userService.update(user);
    //            }
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //            return FsResponseGen.fail();
    //        }
    //        return response;
    //    }

    @Override
    public FsResponse getTrillItemList(FsPage page, String query) {
        GetTrillItemListReq req = new GetTrillItemListReq();
        req.setPage(page.getPageNo());
        req.setPagesize(page.getPageSize());
        //        req.setCat("0");
        //        req.setField("hours");
        if (Objects.nonNull(query)) {
            req.setKeyword(query);
        }
        YsClient client = new YsClient("http://api.web.ecapi.cn/platform/getTrillItemList", configSet.getYunShang().getAppKey());
        FsResponse response;
        try {
            response = client.execute(req, Object.class);
        } catch (Exception e) {
            e.printStackTrace();
            return FsResponseGen.fail();
        }
        if (response.isSuccess()) {
            String jsonArray = JSONObject.parseObject(response.getData().toString()).getString("list");
            response.setData(transVideo(JSONArray.parseArray(jsonArray, GetTrillItemListResp.class)));
        }
        return response;
    }

    @Override
    public FsResponse doItemHighCommissionPromotionLink(Long itemId) {
        ItemHighCommissionPromotionLinkReq req = new ItemHighCommissionPromotionLinkReq();
        req.setItemid(itemId);
        req.setPid("mm_1023840183_2039450276_110863550207");
        req.setTbname("zhangfeng_tech");
        YsClient client = new YsClient("http://api.web.ecapi.cn/taoke/doItemHighCommissionPromotionLink", configSet.getYunShang().getAppKey());
        try {
            return client.execute(req, ItemHighCommissionPromotionLinkResp.class);
        } catch (Exception e) {
            e.printStackTrace();
            return FsResponseGen.fail();
        }
    }

    @Override
    public FsResponse doItemHighCommissionPromotionLinkByTpwd(String tpwdcode) {
        ItemHighCommissionPromotionLinkByTpwdReq req = new ItemHighCommissionPromotionLinkByTpwdReq();
        req.setTpwdcode(tpwdcode);
        req.setPid("mm_1023840183_2039450276_110863550207");
        req.setTbname("zhangfeng_tech");
        YsClient client = new YsClient("http://api.web.ecapi.cn/taoke/doItemHighCommissionPromotionLinkByTpwd", configSet.getYunShang().getAppKey());
        try {
            FsResponse response = client.execute(req, ItemHighCommissionPromotionLinkResp.class);
            if (response.isSuccess()) {
                return itemInfoGet((ItemHighCommissionPromotionLinkResp) response.getData());
            } else {
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return FsResponseGen.fail();
        }
    }

    @Override
    public FsResponse tbkOrderDetailsGet(Long userId, String startTime, String endTime) {
        Contracts.assertNotEmpty(startTime, YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotEmpty(endTime, YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

        TbkOrderDetailsGetReq req = new TbkOrderDetailsGetReq();
        req.setStart_time(startTime);
        req.setEnd_time(endTime);
        req.setTbname("zhangfeng_tech");

        YsClient client = new YsClient("http://api.web.ecapi.cn/taoke/tbkOrderDetailsGet", configSet.getYunShang().getAppKey());
        FsResponse response;
        //        try {
        //            response = client.execute(req, GetTbkQdBeiAnResp.class);
        //            if (response.isSuccess()) {
        //                GetTbkQdBeiAnResp getTbkQdBeiAnResp = (GetTbkQdBeiAnResp) response.getData();
        //                //更新用户表
        //                User user = new User();
        //                user.setId(userId);
        //                user.setRelationId(getTbkQdBeiAnResp.getRelation_id());
        //                user.setSpecialId(getTbkQdBeiAnResp.getSpecial_id());
        //                userService.update(user);
        //            }
        //        } catch (Exception e) {
        //            e.printStackTrace();
        //            return FsResponseGen.fail();
        //        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FsResponse createDaily(String content, Date date) {
        //只有一个生效的，将其他生效变未生效
        Example example = new Example(FanliDaily.class);
        //        0 删除 1生效
        example.createCriteria().andEqualTo("status", 1).andBetween("utime", DateUtils.formatDate(date, "yyyy-MM-dd 00:00:00"), DateUtils.formatDate(date, "yyyy-MM-dd 23:59:59"));
        FanliDaily daily = new FanliDaily();
        daily.setStatus(0);
        fanliDailyMapper.updateByExampleSelective(daily, example);

        FanliDaily daily1 = new FanliDaily();
        daily1.setContent(content);
        daily1.setStatus(1);
        daily1.setCtime(new Date());
        daily1.setUtime(date);
        fanliDailyMapper.insertSelective(daily1);
        return FsResponseGen.success();
    }

    @Override
    public FsResponse getDaily() {
        Example example = new Example(FanliDaily.class);
        //        0 删除 1生效
        example.createCriteria().andEqualTo("status", 1);
        example.setOrderByClause("utime desc");
        List<FanliDaily> dailyList = fanliDailyMapper.selectByExample(example);
        return FsResponseGen.successData(dailyList.size() > 0 ? dailyList.get(0) : null);
    }

    @Override
    public FanliGoodsReceiveDto getFanliGoodsReceiveDto(FanliGoodsReceive v) {
        FanliGoodsReceiveDto dto = new FanliGoodsReceiveDto();
        dto.setCommissionRate(v.getCommissionRate());
        dto.setCouponAmount(v.getCouponAmount());
        dto.setCouponShareUrl(v.getCouponShareUrl());
        dto.setCtime(DateUtils.formatDate(v.getUtime()));
        dto.setId(v.getId());
        dto.setPictUrl(v.getPictUrl());
        dto.setRealMoney(v.getRealMoney());
        if (v.getStatus() == 3) {
            dto.setRefuseReason(v.getRefuseReason());
        }
        dto.setReservePrice(v.getReservePrice());
        dto.setStatus(v.getStatus());
        dto.setTitle(v.getTitle());
        dto.setUrl(v.getUrl());
        dto.setUserId(v.getUserId());
        dto.setUserType(v.getUserType());
        dto.setUtime(DateUtils.formatDate(v.getUtime()));
        dto.setZkFinalPrice(v.getZkFinalPrice());
        dto.setReferId(v.getReferId());

        String smallImgs = v.getSmallImages();
        if (StringUtils.isNotEmpty(smallImgs)) {
            dto.setSmallImages(JSONArray.parseArray(smallImgs, String.class));
        } else {
            dto.setSmallImages(new ArrayList<>());
        }
        return dto;
    }

    @Override
    public FanliGiveAndGoodsDetailDto getFanliGiveAndReceiveDetailDto(FanliGiveAndGoodsDetailDto v) {
        String smallImgs = v.getSmallImagesStr();
        if (StringUtils.isNotEmpty(smallImgs)) {
            v.setSmallImages(JSONArray.parseArray(smallImgs, String.class));
        } else {
            v.setSmallImages(new ArrayList<>());
        }
        v.setSmallImagesStr(null);

        String imgs = v.getImgsStr();
        if (StringUtils.isNotEmpty(imgs)) {
            v.setImgs(JSONArray.parseArray(imgs, String.class));
        } else {
            v.setImgs(null);
        }
        v.setImgsStr(null);
        return v;
    }
}
